// 权限管理工具函数

// 角色定义
export const ROLES = {
  PURCHASER: 'purchaser',      // 采购员
  BUSINESS: 'business',         // 业务员
  LOGISTICS: 'logistics',      // 物流专员
  DATA_MAINTAINER: 'dataMaintainer', // 数据维护员
  FINANCE: 'finance',          // 财务专员
  ADMIN: 'admin'               // 系统管理员
}

// 页面权限配置
export const PAGE_PERMISSIONS = {
  [ROLES.PURCHASER]: [
    'home', 'vehicle-list', 'vehicle-detail', 'monitor', 'alerts', 'profile', 'purchase'
  ],
  [ROLES.BUSINESS]: [
    'home', 'vehicle-list', 'vehicle-detail', 'monitor', 'alerts', 'profile', 'transfer'
  ],
  [ROLES.LOGISTICS]: [
    'home', 'vehicle-list', 'vehicle-detail', 'monitor', 'alerts', 'profile', 'logistics'
  ],
  [ROLES.DATA_MAINTAINER]: [
    'home', 'vehicle-list', 'vehicle-detail', 'monitor', 'alerts', 'profile', 'data'
  ],
  [ROLES.FINANCE]: [
    'home', 'vehicle-list', 'vehicle-detail', 'monitor', 'alerts', 'profile', 'finance'
  ],
  [ROLES.ADMIN]: ['*'] // 所有权限
}

// 操作权限配置
export const OPERATION_PERMISSIONS = {
  // 车辆操作权限
  vehicle: {
    [ROLES.PURCHASER]: ['create', 'edit', 'view', 'delete'],
    [ROLES.BUSINESS]: ['view', 'edit'],
    [ROLES.LOGISTICS]: ['view'],
    [ROLES.DATA_MAINTAINER]: ['view', 'edit'],
    [ROLES.FINANCE]: ['view'],
    [ROLES.ADMIN]: ['*']
  },
  // 状态操作权限
  status: {
    purchasing: [ROLES.PURCHASER],
    inspecting: [ROLES.PURCHASER],
    transferring: [ROLES.BUSINESS],
    exporting: [ROLES.BUSINESS],
    shipping: [ROLES.LOGISTICS],
    exported: [ROLES.LOGISTICS]
  },
  // 资料操作权限
  documents: {
    basic: [ROLES.PURCHASER, ROLES.BUSINESS, ROLES.LOGISTICS, ROLES.DATA_MAINTAINER],
    inspection: [ROLES.PURCHASER, ROLES.BUSINESS, ROLES.DATA_MAINTAINER],
    transfer: [ROLES.BUSINESS, ROLES.DATA_MAINTAINER],
    logistics: [ROLES.LOGISTICS, ROLES.DATA_MAINTAINER],
    finance: [ROLES.FINANCE, ROLES.DATA_MAINTAINER]
  }
}

// 获取用户角色
export const getUserRole = () => {
  // 从本地存储或全局状态获取用户角色
  const userInfo = uni.getStorageSync('userInfo')
  return userInfo?.role || ROLES.PURCHASER
}

// 检查页面访问权限
export const hasPagePermission = (pageName) => {
  const userRole = getUserRole()
  const userPermissions = PAGE_PERMISSIONS[userRole] || []
  return userPermissions.includes('*') || userPermissions.includes(pageName)
}

// 检查操作权限
export const hasOperationPermission = (operation, resource = 'vehicle') => {
  const userRole = getUserRole()
  const permissions = OPERATION_PERMISSIONS[resource] || {}
  const userPermissions = permissions[userRole] || []
  return userPermissions.includes('*') || userPermissions.includes(operation)
}

// 检查状态操作权限
export const hasStatusPermission = (status) => {
  const userRole = getUserRole()
  const statusPermissions = OPERATION_PERMISSIONS.status[status] || []
  return statusPermissions.includes(userRole) || statusPermissions.includes(ROLES.ADMIN)
}

// 检查资料操作权限
export const hasDocumentPermission = (documentType) => {
  const userRole = getUserRole()
  const documentPermissions = OPERATION_PERMISSIONS.documents[documentType] || []
  return documentPermissions.includes(userRole) || documentPermissions.includes(ROLES.ADMIN)
}

// 过滤数据权限
export const filterDataByRole = (data, filterType = 'status') => {
  const userRole = getUserRole()
  
  if (userRole === ROLES.ADMIN) {
    return data
  }
  
  switch (filterType) {
    case 'status':
      return filterByStatus(data, userRole)
    case 'documents':
      return filterByDocuments(data, userRole)
    default:
      return data
  }
}

// 按状态过滤数据
const filterByStatus = (data, userRole) => {
  const statusMap = {
    [ROLES.PURCHASER]: ['purchasing', 'inspecting'],
    [ROLES.BUSINESS]: ['transferring', 'exporting'],
    [ROLES.LOGISTICS]: ['shipping', 'exported'],
    [ROLES.DATA_MAINTAINER]: ['*'], // 数据维护员可以查看所有状态
    [ROLES.FINANCE]: ['*'] // 财务专员可以查看所有状态
  }
  
  const allowedStatuses = statusMap[userRole] || []
  if (allowedStatuses.includes('*')) {
    return data
  }
  
  return data.filter(item => allowedStatuses.includes(item.status))
}

// 按资料类型过滤数据
const filterByDocuments = (data, userRole) => {
  const documentMap = {
    [ROLES.PURCHASER]: ['basic', 'inspection'],
    [ROLES.BUSINESS]: ['basic', 'inspection', 'transfer'],
    [ROLES.LOGISTICS]: ['basic', 'logistics'],
    [ROLES.DATA_MAINTAINER]: ['*'],
    [ROLES.FINANCE]: ['basic', 'finance']
  }
  
  const allowedDocuments = documentMap[userRole] || []
  if (allowedDocuments.includes('*')) {
    return data
  }
  
  return data.filter(item => {
    // 根据资料类型过滤
    return allowedDocuments.some(docType => item.documentTypes?.includes(docType))
  })
}

// 权限指令
export const permissionDirective = {
  mounted(el, binding) {
    const { value } = binding
    const hasPermission = checkPermission(value)
    
    if (!hasPermission) {
      el.style.display = 'none'
    }
  }
}

// 检查权限
const checkPermission = (permission) => {
  if (typeof permission === 'string') {
    return hasOperationPermission(permission)
  } else if (typeof permission === 'object') {
    const { operation, resource, status, documentType } = permission
    
    if (operation && resource) {
      return hasOperationPermission(operation, resource)
    } else if (status) {
      return hasStatusPermission(status)
    } else if (documentType) {
      return hasDocumentPermission(documentType)
    }
  }
  
  return false
}

// 权限守卫
export const permissionGuard = (to, from, next) => {
  const pageName = to.name || to.path.split('/').pop()
  
  if (hasPagePermission(pageName)) {
    next()
  } else {
    uni.showToast({
      title: '没有访问权限',
      icon: 'none'
    })
    next(false)
  }
}

// 获取角色显示名称
export const getRoleDisplayName = (role) => {
  const roleNames = {
    [ROLES.PURCHASER]: '采购员',
    [ROLES.BUSINESS]: '业务员',
    [ROLES.LOGISTICS]: '物流专员',
    [ROLES.DATA_MAINTAINER]: '数据维护员',
    [ROLES.FINANCE]: '财务专员',
    [ROLES.ADMIN]: '系统管理员'
  }
  return roleNames[role] || role
}

// 获取角色颜色
export const getRoleColor = (role) => {
  const roleColors = {
    [ROLES.PURCHASER]: '#3b82f6', // 蓝色
    [ROLES.BUSINESS]: '#10b981',  // 绿色
    [ROLES.LOGISTICS]: '#f97316', // 橙色
    [ROLES.DATA_MAINTAINER]: '#8b5cf6', // 紫色
    [ROLES.FINANCE]: '#ef4444',   // 红色
    [ROLES.ADMIN]: '#1f2937'      // 深灰色
  }
  return roleColors[role] || '#6b7280'
}

// 权限工具类
export class PermissionManager {
  constructor() {
    this.userRole = getUserRole()
  }
  
  // 检查是否有权限
  hasPermission(permission) {
    return checkPermission(permission)
  }
  
  // 检查页面权限
  canAccessPage(pageName) {
    return hasPagePermission(pageName)
  }
  
  // 检查操作权限
  canPerformOperation(operation, resource = 'vehicle') {
    return hasOperationPermission(operation, resource)
  }
  
  // 检查状态权限
  canEditStatus(status) {
    return hasStatusPermission(status)
  }
  
  // 过滤数据
  filterData(data, filterType = 'status') {
    return filterDataByRole(data, filterType)
  }
  
  // 获取用户角色信息
  getUserRoleInfo() {
    return {
      role: this.userRole,
      displayName: getRoleDisplayName(this.userRole),
      color: getRoleColor(this.userRole)
    }
  }
}

// 创建权限管理器实例
export const permissionManager = new PermissionManager()

// 导出默认权限管理器
export default permissionManager 